// 当前选中的API端点
let currentEndpoint = '/api/departments';

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 导航菜单点击事件
    document.getElementById('departments-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/departments';
        document.getElementById('section-title').textContent = '部门管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('employees-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/employees';
        document.getElementById('section-title').textContent = '员工管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('projects-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/projects';
        document.getElementById('section-title').textContent = '项目管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('products-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/products';
        document.getElementById('section-title').textContent = '产品管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('orders-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/orders';
        document.getElementById('section-title').textContent = '订单管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('payments-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        currentEndpoint = '/api/payments';
        document.getElementById('section-title').textContent = '支付管理';
        document.getElementById('hibernate-examples-card').style.display = 'none';
    });
    
    document.getElementById('hibernate-examples-link').addEventListener('click', function(e) {
        e.preventDefault();
        setActiveLink(this);
        document.getElementById('section-title').textContent = 'Hibernate示例';
        document.getElementById('hibernate-examples-card').style.display = 'block';
    });
    
    // 操作按钮点击事件
    document.getElementById('fetch-data').addEventListener('click', function() {
        fetchData(currentEndpoint);
    });
    
    document.getElementById('create-item').addEventListener('click', function() {
        createItem(currentEndpoint);
    });
    
    document.getElementById('update-item').addEventListener('click', function() {
        updateItem(currentEndpoint);
    });
    
    document.getElementById('delete-item').addEventListener('click', function() {
        deleteItem(currentEndpoint);
    });
    
    // Hibernate示例按钮点击事件
    document.getElementById('session-demo').addEventListener('click', function() {
        fetchData('/api/hibernate-examples/session-demo', 'hibernate');
    });
    
    document.getElementById('hql-demo').addEventListener('click', function() {
        fetchData('/api/hibernate-examples/hql-demo', 'hibernate');
    });
    
    document.getElementById('criteria-demo').addEventListener('click', function() {
        fetchData('/api/hibernate-examples/criteria-demo', 'hibernate');
    });
    
    document.getElementById('entity-lifecycle-demo').addEventListener('click', function() {
        fetchData('/api/hibernate-examples/entity-lifecycle-demo', 'hibernate');
    });
    
    document.getElementById('relationship-demo').addEventListener('click', function() {
        fetchData('/api/hibernate-examples/relationship-demo', 'hibernate');
    });
    
    document.getElementById('batch-insert').addEventListener('click', function() {
        fetchData('/api/hibernate-performance/batch-insert', 'hibernate');
    });
    
    document.getElementById('batch-update').addEventListener('click', function() {
        fetchData('/api/hibernate-performance/batch-update', 'hibernate');
    });
    
    document.getElementById('batch-delete').addEventListener('click', function() {
        fetchData('/api/hibernate-performance/batch-delete', 'hibernate');
    });
    
    document.getElementById('pagination').addEventListener('click', function() {
        fetchData('/api/hibernate-performance/pagination', 'hibernate');
    });
});

// 设置活动链接
function setActiveLink(element) {
    // 移除所有链接的active类
    document.querySelectorAll('.list-group-item').forEach(function(el) {
        el.classList.remove('active');
    });
    
    // 为当前点击的链接添加active类
    element.classList.add('active');
}

// 获取数据
function fetchData(endpoint, resultType = 'default') {
    fetch(endpoint)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (resultType === 'hibernate') {
                document.getElementById('hibernate-result-display').textContent = JSON.stringify(data, null, 2);
            } else {
                document.getElementById('result-display').textContent = JSON.stringify(data, null, 2);
            }
        })
        .catch(error => {
            if (resultType === 'hibernate') {
                document.getElementById('hibernate-result-display').textContent = '错误: ' + error.message;
            } else {
                document.getElementById('result-display').textContent = '错误: ' + error.message;
            }
        });
}

// 创建项目
function createItem(endpoint) {
    let newItem;
    
    switch(endpoint) {
        case '/api/departments':
            newItem = {
                name: 'New Department ' + new Date().getTime(),
                description: '这是一个新创建的部门'
            };
            break;
        case '/api/employees':
            newItem = {
                firstName: 'New',
                lastName: 'Employee',
                email: 'new.employee' + new Date().getTime() + '@example.com',
                salary: 60000,
                status: 'ACTIVE',
                department: { id: 1 }
            };
            break;
        case '/api/projects':
            newItem = {
                name: 'New Project ' + new Date().getTime(),
                description: '这是一个新创建的项目',
                startDate: new Date().toISOString().split('T')[0],
                endDate: new Date(new Date().setMonth(new Date().getMonth() + 6)).toISOString().split('T')[0],
                status: 'PLANNING'
            };
            break;
        case '/api/products':
            newItem = {
                name: 'New Product ' + new Date().getTime(),
                description: '这是一个新创建的产品',
                price: 199.99,
                stockQuantity: 100,
                category: 'ELECTRONICS'
            };
            break;
        default:
            document.getElementById('result-display').textContent = '不支持的操作';
            return;
    }
    
    fetch(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(newItem)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应错误: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        document.getElementById('result-display').textContent = '创建成功:\n' + JSON.stringify(data, null, 2);
    })
    .catch(error => {
        document.getElementById('result-display').textContent = '错误: ' + error.message;
    });
}

// 更新项目
function updateItem(endpoint) {
    // 首先获取第一个项目
    fetch(endpoint)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (!data || data.length === 0) {
                throw new Error('没有可更新的数据');
            }
            
            // 获取第一个项目
            const item = data[0];
            const id = item.id;
            
            // 根据不同的端点进行不同的更新
            switch(endpoint) {
                case '/api/departments':
                    item.description = '更新的部门描述 ' + new Date().getTime();
                    break;
                case '/api/employees':
                    item.salary = parseFloat(item.salary) + 5000;
                    break;
                case '/api/projects':
                    item.status = 'IN_PROGRESS';
                    break;
                case '/api/products':
                    item.price = parseFloat(item.price) * 1.1;
                    break;
                default:
                    throw new Error('不支持的操作');
            }
            
            // 发送更新请求
            return fetch(`${endpoint}/${id}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(item)
            });
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            document.getElementById('result-display').textContent = '更新成功:\n' + JSON.stringify(data, null, 2);
        })
        .catch(error => {
            document.getElementById('result-display').textContent = '错误: ' + error.message;
        });
}

// 删除项目
function deleteItem(endpoint) {
    // 首先获取所有项目
    fetch(endpoint)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (!data || data.length === 0) {
                throw new Error('没有可删除的数据');
            }
            
            // 获取最后一个项目的ID
            const id = data[data.length - 1].id;
            
            // 发送删除请求
            return fetch(`${endpoint}/${id}`, {
                method: 'DELETE'
            });
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            document.getElementById('result-display').textContent = '删除成功';
        })
        .catch(error => {
            document.getElementById('result-display').textContent = '错误: ' + error.message;
        });
}